<style lang='scss'>
#data-query {
  .mt15 {
    margin-top: 15px;
  }
}
</style>
<template>
  <div id="data-query">
    <el-form
      class="mt20 mb20"
      :inline="true"
      ref="searchForm"
      :model="searchForm"
      :rules="searchFormRules"
      label-width="100px"
      style="background-color:white;padding:20px 10px;"
      @submit.native.prevent
    >
      <el-form-item prop="dbName" label="数据库名">
        <el-select placeholder="请选择" v-model="searchForm.dbName" @change="handleDBNameChange">
          <el-option v-for="item in dbNameOpts" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="tableName" label="数据表名">
        <el-select placeholder="请选择" v-model="searchForm.tableName">
          <el-option v-for="item in tableNameOpts" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <el-row>
        <el-col :span="24">
          <el-form-item label="where条件" prop="whereClauses">
            <el-input type="textarea" style="width:556px;" placeholder="请输入" v-model="searchForm.whereClauses"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-button type="primary" size="small" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button type="warning" size="small" icon="el-icon-refresh" @click="onReset">重置</el-button>
      </el-row>
    </el-form>

    <el-form
      class="mt20 mb20"
      ref="batchForm"
      :model="batchForm"
      :rules="batchFormRules"
      label-width="120px"
      style="background-color:white;padding:20px 10px;"
      @submit.native.prevent
    >
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="setClause" prop="setClause">
            <el-input type="textarea" autosize placeholder="请输入" v-model="batchForm.setClause"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="whereClause" prop="whereClause">
            <el-input type="textarea" autosize placeholder="请输入" v-model="batchForm.whereClause"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="tc">
        <el-button type="primary" size="small" icon="el-icon-edit" @click="onBatchSubmit">批量操作</el-button>
      </div>
    </el-form>

    <div class="data-list-container">
      <el-table
        v-loading="regionLoading"
        element-loading-spinner="el-icon-loading"
        :data="dataQueryList.data"
        border
        style="width:100%;"
        class="m20px"
        ref="multipleTable"
      >
        <el-table-column sortable label="id" width="100">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column sortable label="content">
          <template slot-scope="scope">{{ JSON.stringify(scope.row) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="onOpenDialog({type:'view',row:scope.row})">详情</el-button>

            <el-button size="small" type="text" @click="onOpenDialog({type:'edit',row:scope.row})">更新</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if=" dataQueryList.total > 0 "
        :page-sizes="pagination.pageSizes"
        :page-size="dataQueryList.pageSize"
        :layout="pagination.layout"
        :total="dataQueryList.total"
        :current-page="dataQueryList.pageIndex"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      @close="modifyDialogVisible = false;"
      :visible.sync="modifyDialogVisible"
      class="convert-dialog"
    >
      <el-form
        :model="modifyForm"
        :rules="modifyFormRules"
        ref="modifyForm"
        :label-position="'' | LABEL_POSITION"
        :disabled=" type == 'view' "
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据库名:" label-width="120px">
              <el-input disabled v-model="modifyForm.dbName" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="表名:" label-width="120px">
              <el-input disabled v-model="modifyForm.tableName" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="键值对:" label-width="120px">
              <!-- 内层表格 -->
              <el-table
                v-loading="regionLoading"
                element-loading-spinner="el-icon-loading"
                :data="modifyForm.beanMapping"
                border
                class="form-table"
                id="data-query-table"
                max-height="400"
                @selection-change="handleSelectionChange"
              >
                <el-table-column v-if="type !== 'view'" type="selection" width="55"></el-table-column>
                <el-table-column label="key">
                  <template slot-scope="scope">
                    <el-form-item :prop=" 'beanMapping.' + scope.$index + '.key' " class="mt15">
                      <el-input disabled v-model="scope.row.key" placeholder="请输入"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="value">
                  <template slot-scope="scope">
                    <el-form-item :prop=" 'beanMapping.' + scope.$index + '.value' " class="mt15">
                      <el-input v-model="scope.row.value" placeholder="请输入"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row>
        <el-col :span="24" class="tc mt20">
          <el-button type="primary" v-if=" type != 'view' " @click="onSubmitForm">保存</el-button>
          <el-button type="success" @click="modifyDialogVisible = false;">关闭</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState, mapMutations } from "vuex";
import SELECT_DATA, { getConfigItem } from "src/utils/selectData";
import storage from 'src/utils/storage';
import fetch from "src/utils/fetch";
import { isJSON } from "src/utils/tools";

export default {
  data() {

    const inputWarning = (msg) => {

      return [
        {
          required: true,
          message: msg,
          trigger: "blur,change"
        }
      ];
    };

    return {

      dataQueryList: {
        pageIndex: 1,
        pageSize: 20,
        total: 0,
        data: [],
      },

      title: '',
      type: '',
      modifyDialogVisible: false,

      searchForm: {
        dbName: '',
        tableName: '',
        whereClauses: '',
      },
      searchFormRules: {
        dbName: inputWarning('请选择'),
        tableName: inputWarning('请选择'),
        whereClauses: inputWarning('请输入'),
      },

      dbNameOpts: ['Ultron', 'Galaxy', 'Kepler'],
      tableNameOpts: [],
      selectionRows: [],
      modifyForm: {
        id: '',
        dbName: '',
        tableName: '',
        setClause: '',
        whereClause: '',
        whereClauseArr: [],
      },
      modifyFormRules: {
        dbName: inputWarning('请输入'),
        tableName: inputWarning('请输入'),
        key: inputWarning('请输入'),
        value: inputWarning('请输入'),
      },

      batchForm: {
        setClause: '',
        whereClause: '',
      },
      batchFormRules: {
        setClause: inputWarning('请输入'),
        whereClause: inputWarning('请输入'),
      },


    };
  },
  components: {
  },
  computed: {
    ...mapGetters(["pagination", "regionLoading",]),
  },
  watch: {
    // $route: "handleRouteChange"
  },
  created() {

  },
  mounted() {

    let that = this;
    setTimeout(() => {
      document.querySelector('#data-query').onkeydown = function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];

        if (e && e.keyCode == 13) {
          that.getList();
        }
      }

    }, 100)


  },
  methods: {
    ...mapActions([" ",]),
    onBatchSubmit() {

      let params = {
        "dbName": this.searchForm.dbName,
        "tableName": this.searchForm.tableName,
        "setClause": this.batchForm.setClause,
        "whereClause": this.batchForm.whereClause,
      };

      this.$refs.batchForm.validate(valid => {
        if (valid) {

          this.$confirm("确定要批量更新数据吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {


            fetch({
              url: '/dynamicData/updateData',
              type: "post",
              data: params,
              showRegionLoading: true,
              success: (data) => {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.$refs["batchForm"] && this.$refs["batchForm"].resetFields();
                this.dataQueryList.pageIndex = 1;
                this.getList();
              },
            });
          })

        } else {
          this.$message({
            type: "warning",
            message: "请检查表单必填项!"
          });
        }
      });

    },
    //新增&&编辑保存
    onSubmitForm() {

      let setClause = '';

      if (this.selectionRows.length == 0) {
        return this.$message({
          type: "warning",
          message: "请选择修改项!"
        });
      }

      this.selectionRows.forEach((item, index) => {
        index == 0 ? setClause += item.key + "='" + item.value + "'" : setClause += ' , ' + item.key + "='" + item.value + "'";
      });


      let params = {
        "dbName": this.modifyForm.dbName,
        "tableName": this.modifyForm.tableName,
        "setClause": setClause,
        "whereClause": "id = " + this.modifyForm.id,
      };


      this.$refs.modifyForm.validate(valid => {
        if (valid) {

          this.$confirm("确定要更新数据吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {


            fetch({
              url: '/dynamicData/updateData',
              type: "post",
              data: params,
              showRegionLoading: true,
              success: (data) => {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.modifyDialogVisible = false;
                this.dataQueryList.pageIndex = 1;
                this.getList();
              },
            });
          })

        } else {
          this.$message({
            type: "warning",
            message: "请检查表单必填项!"
          });
        }
      });
    },
    handleSelectionChange(items) {
      this.selectionRows = items;
    },
    onOpenDialog(obj) {

      let id = '',
        beanMapping = [],
        row = JSON.parse(JSON.stringify(obj.row)),
        title = {
          'add': '新增记录',
          'view': '查看记录',
          'edit': '更新记录',
        }[obj.type];

      this.title = title;
      this.type = obj.type;
      this.$refs["modifyForm"] && this.$refs["modifyForm"].resetFields();

      // 过滤到id,id在隐藏域提交
      for (let key in row) {
        key != 'id' ? beanMapping.push({ key: key, value: row[key] }) : id = row[key];
      }

      this.modifyForm = {
        dbName: this.searchForm.dbName,
        tableName: this.searchForm.tableName,
        beanMapping: beanMapping,
        id: id,
      };

      this.modifyDialogVisible = true;
    },
    // 每页显示条数改变
    handleSizeChange(pageSize) {
      this.dataQueryList.pageSize = pageSize;
      this.getList();
    },
    // 页码改变
    handleCurrentChange(pageIndex) {
      this.dataQueryList.pageIndex = pageIndex;
      this.getList();
    },
    handleDBNameChange(value) {

      let that = this;
      fetch({
        url: '/getTables',
        type: "post",
        data: { dbName: value },
        showRegionLoading: true,
        success: (data) => {
          that.tableNameOpts = data || [];
          that.searchForm.tableName = '';
        },
      });
    },
    getList() {
      let that = this;
      let param = {
        dbName: that.searchForm.dbName,
        tableName: that.searchForm.tableName,
        whereClauses: that.searchForm.whereClauses,
        offset: that.dataQueryList.pageIndex,
        rows: that.dataQueryList.pageSize,
      };

      this.$refs.searchForm && this.$refs.searchForm.validate(valid => {
        if (valid) {
          fetch({
            url: '/queryData',
            type: "post",
            data: param,
            showRegionLoading: true,
            success: (res) => {
              let data = res || {};
              that.dataQueryList.total = data.count || 0;
              that.dataQueryList.data = data.resultList || [];
            },
          });
        } else {
          this.$message({
            type: "warning",
            message: "请检查表单必填项!"
          });
        }
      })

    },

    onReset() {
      this.$refs["searchForm"].resetFields();
    }
  }
};
</script>
